<?php
/**
 *
 */
class MessagesController extends AppController {

	public $uses = array('Group', 'User', 'Message');//Necessary Message, but about others I don't know.
	public $helpers = array('Html', 'Form');// $helpers = array('Time');
	public $show_time = true;
	
	public function isAuthorized($user) {
		// Authenticated users should be able to access every function
		return true;
	}

	function unserializesession( $data ) {
	   if(strlen($data) == 0)
		  return array();

	   // match all the session keys and offsets
	   preg_match_all('/(^|;|\})([a-zA-Z0-9_]+)\|/i', $data, $matchesarray, PREG_OFFSET_CAPTURE);

	   $returnArray = array();

	   $lastOffset = null;
	   $currentKey = '';
	   foreach ( $matchesarray[2] as $value ) {
		  $offset = $value[1];
		  if(!is_null( $lastOffset)) {
		     $valueText = substr($data, $lastOffset, $offset - $lastOffset );
		     $returnArray[$currentKey] = unserialize($valueText);
		  }
		  $currentKey = $value[0];

		  $lastOffset = $offset + strlen( $currentKey )+1;
	   }

	   $valueText = substr($data, $lastOffset );
	   $returnArray[$currentKey] = unserialize($valueText);

	   return $returnArray;
	}

	/* Checks every certain time is there new messages from other users
	*/
	function chatHeartbeat() {
		header('Content-type: application/json; charset=UTF-8');
		echo '{';
		if($this->show_time) {
			$cakephp_time = microtime(true);
			echo '"cakephp_time": "'.($cakephp_time-START).'"';
		}
		//Retrieves a list of all system users
		$users = array();
		$result = $this->User->query('SELECT id_user, name FROM users');
		foreach($result as $user) {
			$users[$user['users']['id_user']] = $user['users']['name'];
		}

		//Retrieves messeges those are send to the authenticated user of page request
		$result = $this->Message->query('SELECT * FROM messages WHERE id_receiver='.(int)$this->Auth->user('id_user').' AND recd=0 ORDER BY id_message ASC');
		//$result[0]['messages']['id_sender']);
		$items = '';
		$chatBoxes = array();
		foreach($result as $chat) {
			$chat = $chat['messages'];
			if (!$this->Session->check('Message.openChatBoxes.'.$chat['id_sender']) && $this->Session->check('Message.chatHistory.'.$chat['id_sender']))
				$items = $this->Session->read('Message.chatHistory.'.$chat['id_sender']);

			$chat['text'] = $this->sanitize($chat['text']);

			$items .= '{"s": "0", "f": "'.$chat['id_sender'].'", "fn": "'.$users[$chat['id_sender']].'", "m": "'.$chat['text'].'"},';//JSON########

			$this->Session->write('Message.chatHistory.'.$chat['id_sender'], $this->Session->read('Message.chatHistory.'.$chat['id_sender']).'{
					"s": "0", "f": "'.$chat['id_sender'].'", "fn": "'.$users[$chat['id_sender']].'", "m": "'.$chat['text'].'"},');//JSON###########
		
			$this->Session->delete('Message.tsChatBoxes.'.$chat['id_sender']);
			$this->Session->write('Message.openChatBoxes.'.$chat['id_sender'], $chat['created']);
		}

		$openChatBoxes = $this->Session->read('Message.openChatBoxes');
		if (!empty($openChatBoxes)) {
			foreach ($openChatBoxes as $chatbox => $time) {
				if (!$this->Session->check('Message.tsChatBoxes.'.$chatbox)) {
					$now = time()-strtotime($time);
					$time = date('g:iA M dS', strtotime($time));

					$message = "Sent at $time";
					if ($now > 180) {
						$items .= '{"s": "2", "f": "'.$chatbox.'", "fn": "'.$users[$chatbox].'", "m": "'.$message.'"},';//JSON###########

						if (!$this->Session->check('Message.chatHistory.'.$chatbox))
							$_SESSION['chatHistory'][$chatbox] = '';

						$this->Session->write('Message.chatHistory.'.$chatbox, $this->Session->read('Message.chatHistory.'.$chatbox).'{
							"s": "2", "f": "'.$chatbox.'", "fn": "'.$users[$chatbox].'", "m": "'.$message.'"},');//JSON###########
						$this->Session->write('Message.tsChatBoxes.'.$chatbox, 1);
					}
				}
			}
		}

		$result = $this->Message->query("UPDATE messages SET recd=1 WHERE id_receiver=".(int)$this->Auth->user('id_user')." AND recd=0");

		if ($items != '')
			$items = substr($items, 0, -1);
		
		?>,"items": [<?php echo $items?>],<?php //JSON#############################
		if($this->show_time) {
			echo '"chat_time": "'.(microtime(true)-$cakephp_time).'"';
		}
		die('}');

	}

	/* Sends to user json with his username, id_user and messages that (s)he chat with someone
	*/
	function startChatSession() {
		$items = '';
		$openChatBoxes = $this->Session->read('Message.openChatBoxes');
		if ($this->Session->check('Message.openChatBoxes') && !empty($openChatBoxes)) {
			foreach ($this->Session->read('Message.openChatBoxes') as $chatbox => $void) {
				$items .= $this->Session->read('Message.chatHistory.'.$chatbox);
			}
		}

		if ($items != '')
			$items = substr($items, 0, -1);

		header('Content-type: application/json; charset=UTF-8');//JSON##################
		?>
		{"username": "<?php echo $this->Auth->user('name')?>",
		"id_user": "<?php echo $this->Auth->user('id_user')?>",
		"items": [<?php echo $items;?>],
		<?php
		die('"all_time":"'.(microtime(true)-START).'"}');
	}

	/* Saves a message in db and also saves in session.
	*/
	function sendChat() {
		$from = $this->Auth->user('id_user'); //$this->Session->read('Message.from');
		$to = $this->request->data['to'];
		$ton = $this->request->data['ton'];
		$message = $this->request->data['message'];

		$this->Session->write('Message.openChatBoxes.'.$this->request->data['to'], date('Y-m-d H:i:s', time()));
	
		$messagesan = $this->sanitize($message);

		$this->Session->write('Message.chatHistory.'.$this->request->data['to'], $this->Session->read('Message.chatHistory.'.$this->request->data['to']). '{"s": "1", "f": "'.$to.'", "fn": "'.$ton.'", "m": "'.$messagesan.'"},');//JSON###########
		
		$this->Session->delete('Message.tsChatBoxes.'.$this->request->data['to']);

		$data['Message'] = array('id_sender' => $from, 'sender_name' => $ton, 'id_receiver' => $to, 'text' => $message );
		if ($this->Message->save($data)) die('1');
		else die('0');
	}

	/* Closes the chat box, and deletes session.
	*/
	function closeChat() {
		$this->Session->delete('Message.openChatBoxes.'.$_POST['chatbox']);
		die('1');
	}

	/* Escapes from XSS attacts & ENTER key presses shows like new lines.
	*/
	function sanitize($text) {
		$text = htmlspecialchars($text, ENT_QUOTES);
		return str_replace(array("\r", "\n", '\\'), array('', '<br>', '\\\\'), $text);
	}
}

